<?php

/**
 * 设置
 * 
 * @author ShuangYa
 * @package TBSign
 * @category Controller
 * @link http://www.sylingd.com/
 */

namespace tbsign\controller;
use \Sy;
use \sy\base\Controller;
use \tbsign\libs\Common;

class Setting extends Controller {
	public function __construct() {
		$this->loadModel('member', 'm');
		if (FALSE === ($this->user = $this->m->getLogin())) {
			Sy::httpStatus(403);
			exit;
		}
	}
	public function actionSign() {
		if (Common::isPost()) {
			$BDUSS = $_POST['bduss'];
			$STOKEN = $_POST['stoken'];
			$morethan200 = intval($_POST['morethan200']);
			//检查BDUSS是否为本人
			try {
				$realuser = \TiebaPersonal::getMyInfo($BDUSS);
				$realuser = (array)$realuser;
			} catch (\Exception $e) {
				Common::showAjax(['error' => '验证错误，请重试']);
			}
			if ($realuser['name'] !== $this->user['uname']) {
				Common::showAjax(['error' => 'Cookie无效']);
			}
			$this->m->setUserValue($this->user['uid'], ['uname' => $this->user['uname'], 'bduss' => $BDUSS, 'stoken' => $STOKEN, 'morethan200' => $morethan200]);
			Common::showAjax();
		} else {
			$u = $this->m->get($this->user['uid']);
			!is_array($u) && $u = [];
			Sy::view('setting/sign', $u);
		}
	}
	public function actionTestCookie() {
		$user = $this->m->get($this->user['uid']);
		try {
			$realuser = \TiebaPersonal::getMyInfo($user['bduss']);
			$realuser = (array)$realuser;
		} catch (\Exception $e) {
			Common::showAjax(['error' => '验证错误，请重试']);
		}
		if (!isset($realuser['name'])) {
			Common::showAjax(['error' => 'Cookie无效']);
		}
		Common::showAjax();
	}
	public function actionTestSign() {
		$user = $this->m->get($this->user['uid']);
		try {
			if ($user['morethan200'] == 1) {
				$userlike = \TiebaPersonal::getMyLikeSlow($user['bduss'], $user['stoken'], 10);
			} else {
				$userlike = \TiebaPersonal::getMyLike($user['bduss']);
			}
		} catch (\Exception $e) {
			Common::showAjax(['error' => '无法获取贴吧列表']);
			return;
		}
		//只尝试5个贴吧
		$result = [];
		foreach ($userlike as $tb) {
			$oneResult = ['name' => $tb['name']];
			try {
				$r = \TiebaPersonal::sign($user['bduss'], $tb['name'], $tb['id']);
			} catch (\Exception $e) {
				$oneResult['result'] = 0;
			}
			$oneResult['result'] = $r[0];
			$result[] = $oneResult;
			if (count($result) >= 5) {
				break;
			}
			sleep(0.5);
		}
		Common::showAjax(['result' => $result]);
	}
}
